package com.cherrish.demo.block1;

import lombok.Data;


/**
 * @author cherrish
 * @time 2019-02-15 11:17
 * @name Block
 * @desc:
 */
@Data
public class Block {
    public String hash;
    public String preHash;
    private String data;
    private long timeStamp;

    private int nonce;

    public Block() {
    }

    public Block(String data, String preHash) {
        this.data = data;
        this.preHash = preHash;
        this.timeStamp = System.currentTimeMillis();
        this.hash = calculateHash();
    }

    public String calculateHash() {
        String calculatedhash = StringUtil.applySha256(preHash + Long.toString(timeStamp) + Integer.toString(nonce) +
                data);
        return calculatedhash;
    }

    public void mineBlock(int difficulty) {
        String target = new String(new char[difficulty]).replace('\0', '0');
        while (!hash.substring(0, difficulty).equals(target)) {
            nonce++;
            hash = calculateHash();
        }
        System.out.println("Block Mined!!!" + hash);
    }
}
